package beautiful.butterfly.distributed_service_container.http.mvc.core;

import beautiful.butterfly.distributed_service_container.http.mvc.aop.InterceptorsAndActionExecute;
import beautiful.butterfly.distributed_service_container.http.mvc.http.Request;
import beautiful.butterfly.distributed_service_container.http.mvc.render.Render;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public final class ActionExecute
{

    private static final String Index_Url = "/";
    private static final String Index_Url_To_Action_Url = "/index/index.html";
    private static Logger logger = LoggerFactory.getLogger(ActionExecute.class);

    public ActionExecute(String basePackageName)
    {
        ActionMapping.buildActionMapping(basePackageName);
    }


    /**
     * 只接受.html的请求
     */
    public Render execute(Request request) throws IOException
    {
        String key = request.getUri();
        if (Index_Url.equals(key))
        {// /
            key = Index_Url_To_Action_Url;
        }
        int index = key.lastIndexOf(".html");
        if (index != -1)
        {
            key = key.substring(0, index);
        }
        Action action = ActionMapping.getAction(key);
        if (action == null)
        {
            return null;
        } else
        {
            Controller controller = action.getController();
            ActionReporter.doReport(controller, action);
            return (new InterceptorsAndActionExecute(action, controller)).invoke();

        }

    }

}
